#ifndef CPPSTUDY_MYARRAY_H
#define CPPSTUDY_MYARRAY_H

#include <iostream>

using namespace std;

template<typename T>
class Arr {
private:
    T *address;//指向一个堆空间，这个空间存储真正的数据
    int capacity;//容量
    int size;// 大小
public:
    //构造函数
    Arr(int capacity) {
        //cout<<"Arr的构造函数"<<endl;
        this->capacity = capacity;
        this->size = 0;
        this->address = new T[this->capacity];
    }

    //拷贝构造
    Arr(const Arr &arr) {
        //cout<<"Arr的拷贝构造函数"<<endl;
        this->capacity = arr.capacity;
        this->size = arr.size;
        this->address = new T[this->capacity];//深拷贝
        for (int i = 0; i < this->size; ++i) {//将arr中的数据都拷贝过来
            //如果T为对象，而且还包含指针，必须需要重载 = 操作符，因为这个等号不是 构造 而是赋值，
            // 普通类型可以直接= 但是指针类型需要深拷贝
            this->address[i] = address[i];
        }
    }

    //重载= 操作符  防止浅拷贝问题
    Arr &operator=(const Arr &arr) {
        //cout<<"Arr的operator=函数"<<endl;
        if (this->address != nullptr) {
            delete[] this->address;
            this->capacity = 0;
            this->size = 0;
        }
        this->capacity = arr.capacity;
        this->size = arr.size;
        this->address = new T[this->capacity];
        for (int i = 0; i < this->size; i++) {
            this->address[i] = arr.address[i];
        }
        return *this;
    }

    //重载[] 操作符  arr[0]
    T &operator[](int index) {
        return this->address[index];
    }

    //尾插法
    void pushBack(const T &val) {
        if (this->capacity == this->size) {
            return;
        }
        this->address[this->size] = val;
        this->size++;
    }

    //尾删法
    void popBack() {
        if (this->size == 0) {
            return;
        }
        this->size--;
    }

    //获取数组容量
    int getCapacity() {
        return this->capacity;
    }

    //获取数组大小
    int getSize() {
        return this->size;
    }

    //析构
    ~Arr() {
        //cout<<"Arr的析构函数"<<endl;
        if (this->address != nullptr) {
            delete[] this->address;
            this->address = nullptr;
            this->capacity = 0;
            this->size = 0;
        }
    }
};

#endif //CPPSTUDY_MYARRAY_H